<template>
  <div class="sports-records">
    <div class="header">
      <h2>运动记录</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增记录
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="运动类型">
        <el-select v-model="searchForm.sport_type" placeholder="请选择运动类型" clearable>
          <el-option label="跑步" value="跑步" />
          <el-option label="游泳" value="游泳" />
          <el-option label="骑行" value="骑行" />
          <el-option label="瑜伽" value="瑜伽" />
          <el-option label="健身" value="健身" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="recordList" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="record_date" label="记录日期" width="120">
        <template #default="{ row }">
          {{ formatDateTime(row.record_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="运动类型" width="120" />
      <el-table-column prop="during" label="运动时长(分钟)" width="120" />
      <el-table-column prop="distance" label="运动距离(km)" width="120" />
      <el-table-column prop="calorie" label="消耗卡路里" width="120" />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 记录表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose"
    >
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="100px">
        <el-form-item label="记录日期" prop="record_date">
          <el-date-picker
            v-model="recordForm.record_date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="运动类型" prop="type">
          <el-select v-model="recordForm.type" placeholder="请选择运动类型" style="width: 100%">
            <el-option label="跑步" value="跑步" />
            <el-option label="游泳" value="游泳" />
            <el-option label="骑行" value="骑行" />
            <el-option label="瑜伽" value="瑜伽" />
            <el-option label="健身" value="健身" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运动时长(分钟)" prop="during">
              <el-input-number v-model="recordForm.during" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运动距离(km)" prop="distance">
              <el-input-number v-model="recordForm.distance" :min="0" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="消耗卡路里" prop="calorie">
          <el-input-number v-model="recordForm.calorie" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getSportsRecords, createSportsRecord, updateSportsRecord, deleteSportsRecord } from '@/api/health'
import { formatDateTime } from '@/utils'
import type { SportsRecord, SportsRecordForm } from '@/types/health'

const loading = ref(false)
const dialogVisible = ref(false)
const isAdd = ref(true)
const recordFormRef = ref()

const searchForm = reactive({
  dateRange: [],
  sport_type: ''
})

const recordForm = reactive<SportsRecordForm>({
  record_date: '',
  type: '',
  during: 0,
  distance: 0,
  calorie: 0
})

const recordList = ref<SportsRecord[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const recordRules = {
  record_date: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  type: [{ required: true, message: '请选择运动类型', trigger: 'change' }],
  during: [{ required: true, message: '请输入运动时长', trigger: 'blur' }]
}

const dialogTitle = computed(() => isAdd.value ? '新增运动记录' : '编辑运动记录')

// 获取记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.size
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.start_date = searchForm.dateRange[0]
      params.end_date = searchForm.dateRange[1]
    }
    
    if (searchForm.sport_type) {
      params.sport_type = searchForm.sport_type
    }
    
    const response = await getSportsRecords(params)
    recordList.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取记录列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchRecords()
}

// 重置搜索
const handleReset = () => {
  searchForm.dateRange = []
  searchForm.sport_type = ''
  pagination.current = 1
  fetchRecords()
}

// 新增记录
const handleAdd = () => {
  isAdd.value = true
  Object.assign(recordForm, {
    record_date: new Date().toISOString().split('T')[0],
    type: '',
    during: 0,
    distance: 0,
    calorie: 0
  })
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row: SportsRecord) => {
  isAdd.value = false
  Object.assign(recordForm, { ...row })
  dialogVisible.value = true
}

// 删除记录
const handleDelete = async (row: SportsRecord) => {
  try {
    await ElMessageBox.confirm('确定删除该记录吗？', '提示', {
      type: 'warning'
    })
    
    // 确保id存在
    if (row.id) {
      await deleteSportsRecord(row.id)
      ElMessage.success('删除成功')
      fetchRecords()
    } else {
      ElMessage.error('记录ID不存在')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!recordFormRef.value) return
  
  try {
    const valid = await recordFormRef.value.validate()
    if (!valid) return
    
    if (isAdd.value) {
      await createSportsRecord(recordForm)
      ElMessage.success('新增成功')
    } else {
      await updateSportsRecord(recordForm.id!, recordForm)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchRecords()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  recordFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchRecords()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchRecords()
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.sports-records {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>